package com.k2data.app.k2bq.skylar360.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.k2data.app.k2bq.skylar360.request.RequestConf;
import com.k2data.app.k2bq.skylar360.utils.exception.DecryptException;
import okhttp3.*;

import java.io.IOException;

public class OkHttpUtils {

    public static JSONObject send(OkHttpClient client, RequestConf rc) throws IOException {
        if ("GET".equals(rc.getMethod())) {
            return sendGet(client, rc);
        } else {
            return sendPost(client, rc);
        }
    }

    private static JSONObject sendGet(OkHttpClient client, RequestConf rc) throws IOException {
        String url = rc.getUrl();

        Request request = new Request.Builder().url(url).build();
        return decryptAES(client.newCall(request).execute());
    }

    private static JSONObject sendPost(OkHttpClient client, RequestConf rc) throws IOException {
        String url = rc.getUrl();
        String json = (rc.getBody() == null || rc.getBody().size() == 0) ? rc.getBodyStr() : JSON.toJSONString(rc.getBody());

        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
        Request request = new Request.Builder().url(url).post(body).build();
        return decryptAES(client.newCall(request).execute());
    }

    private static JSONObject decryptAES(Response response) throws IOException {
        try {
            return JSON.parseObject(DecryptAES.decryptAES(response.body().string()));
        } catch (DecryptException e) {
            System.out.println(e.getMessage());
            return null;
        }
    }

}
